package service;

import mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import pojo.User;
import utils.SqlSessionFactoryUtils;

public class UserService {
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();

    public User login(String username,String password){
        SqlSession sqlSession = factory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.selectByUsername(username);
        if (user!=null){
            if (password.equals(user.getPassword())) {
                //登录成功
                return user;
            }else {
                //因为密码错误，导致登录失败
                return null;
            }
        }
        //因为用户不存在导致登录失败
        return null;
    }
    //注册用户
    public boolean register(String username,String password){
        SqlSession sqlSession = factory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //1.此用户名是否可以被注册
        User user = userMapper.selectByUsername(username);
        if (user!=null){
            //如果此条件成立，数据库已有该名称用户
            return false;
        }

        //2.如果能被注册，则执行注册操作
        User newUser = new User(null, username, password);
        int i = userMapper.add(newUser); //i添加成功的用户数量
        sqlSession.commit();
        sqlSession.close();
        return i>0;
    }


    //检查用户名是否存在
    public boolean checkUsername(String username){
        SqlSession sqlSession = factory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //1.此用户名是否可以被注册
        User user = userMapper.selectByUsername(username);
        if (user!=null){
            //如果此条件成立，数据库已有该名称用户
            return true;
        }

        //2.如果能被注册，则执行注册操作
       sqlSession.close();
        return false;
    }

}
